#!/usr/bin/env bash
set -e

rebuildImageFlag=$1
# 拉取最新代码
git pull

# 删除base镜像
if [ "$rebuildImageFlag" == "true" ]; then
  if [ -n "$(docker images -aqf "reference=my-blog:base")" ]; then
    echo "删除base镜像"
    docker rmi $(docker images -aqf "reference=my-blog:base")
    echo "============"
  fi
  # 构建base镜像
  echo "构建base镜像"
  sh release/base/build.sh
  echo "============"
fi

# 停止并删除web容器
if [ -n "$(docker ps -aqf "name=my-blog")" ]; then
  echo "停止并删除web容器"
  docker stop $(docker ps -aqf "name=my-blog")
  docker rm $(docker ps -aqf "name=my-blog")
  echo "============"
fi
# 删除web镜像
if [ -n "$(docker images -aqf "reference=my-blog:web")" ]; then
  echo "删除web镜像"
  docker rmi $(docker images -aqf "reference=my-blog:web")
  echo "============"
fi
# 构建web镜像
echo "构建web镜像"
sh release/docker/build.sh
echo "============"
# 运行web容器
echo "运行web容器"
docker run -p 80:80 -d --name my-blog my-blog:web
echo "===devops_finish==="
